﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MaxLeaf.Platform.DataContract;
using CommonsLib.DB;
using MaxLeaf.Platform.DALImplementation;
using MaxLeaf.Platform.Functions;
using CommonsLib.Utility;
using MaxLeaf.Platform.Commons;
using MaxLeaf.Platform.Contract;
using System.Transactions;
using CommonsLib.Utility;
using CommonsLib.Settings;

namespace MaxLeaf.Platform.BLLImplementation
{
    public class poReqProcessor :   IPoReqProcess
    {



        public poOrderHdrDataModel PostBatch(int intEnterUserId, List<int> lstReqHdrKeys)
        {
            poOrderHdrDataModel model = null;
            using (System.Transactions.TransactionScope ts = DataFunc.CreateTransactionScope())
            {
                foreach (int intReqHdrID in lstReqHdrKeys)
                {
                    model = Post(intEnterUserId, intReqHdrID, null);
                }
                ts.Complete();
            }
            return model;
        }
        public poOrderHdrDataModel Post(int intEnterUserId, int intReqHdrID, List<int> lstReqDtlKeys)
        {
            poReqHdrBLL bllReqHdr =new poReqHdrBLL();
            poReqDtlBLL bllReqDtl = new poReqDtlBLL(); ;
            if (lstReqDtlKeys == null || lstReqDtlKeys.Count == 0)
            {
                //得到unposted dtl
                lstReqDtlKeys = bllReqDtl.GetUnpostKeys(intReqHdrID);
                if (lstReqDtlKeys == null || lstReqDtlKeys.Count == 0)
                {
                    throw new MaxLeafException(string.Format(Const.MSG_NoDataToPost, intReqHdrID));
                }
            }

            poReqHdrDataModel modelReqHdr = new poReqHdrDataModel();
            modelReqHdr = (poReqHdrDataModel)bllReqHdr.Select(modelReqHdr, intReqHdrID);
            if (modelReqHdr.Posted )
            {
                throw new MaxLeafException(string.Format(Const.MSG_NoDataToPost, intReqHdrID));
            }

            BaseBLL bllOrderHdr = BaseBLL.GetDataModelBLL("poOrderHdrDataModel");
            poOrderDtlBLL bllOrderDtl = new poOrderDtlBLL();

            //插入poOrderHdr.Finterid
            poOrderHdrDataModel modelOrderHdr = Post_InitHdr((poOrderHdrBLL)bllOrderHdr, modelReqHdr, intEnterUserId);

            List<poOrderDtlDataModel> lstOrderDtl = new List<poOrderDtlDataModel>();
            for (int i = 0; i < lstReqDtlKeys.Count; i++)
            {

                poReqDtlDataModel modelReqDtl = new poReqDtlDataModel();
                modelReqDtl = (poReqDtlDataModel)bllReqDtl.Select(modelReqDtl, lstReqDtlKeys[i]);
                //插入poOrderHdr.Finterid
                lstOrderDtl.Add(Post_InitDtl(bllOrderDtl, modelOrderHdr.Key, modelReqDtl));

            }

            using (System.Transactions.TransactionScope ts = DataFunc.CreateTransactionScope())
            {
                using (DBAccess dbConOrder = new DBAccess(DataFunc.GetConnectionInfo(Const.DB_SCPSEOrder)))
                {
                    try
                    {
                        //dbConOrder.BeginTrans();

                        if (!bllReqHdr.CurrentBRL.CanPost(dbConOrder, bllReqHdr.CurrentDAL, "poReqHdr", "FinterId", intReqHdrID))
                        {
                            throw new MaxLeafException(string.Format(Const.MSG_NoDataToPost, intReqHdrID));
                        }
                        //保存 poOrderHdr 其他数据
                        modelOrderHdr = (poOrderHdrDataModel)bllOrderHdr.Update(dbConOrder, modelOrderHdr);



                        for (int i = 0; i < lstReqDtlKeys.Count; i++)
                        {
                            if (bllReqDtl.CurrentBRL.CanPost(dbConOrder, bllReqDtl.CurrentDAL, "poReqDtl", "DtlId", lstReqDtlKeys[i]))
                            {
                                //保存 poOrderDtl 其他数据
                                lstOrderDtl[i] = (poOrderDtlDataModel)bllOrderDtl.Update(dbConOrder, lstOrderDtl[i]);
                                //写入来源 ReqDtl key
                                bllOrderDtl.SetReqDtlId(dbConOrder, lstOrderDtl[i].Key, intReqHdrID, lstReqDtlKeys[i]);

                                //设置ReqDtl Post标志
                                bllReqDtl.SetPosted(dbConOrder, lstReqDtlKeys[i], lstOrderDtl[i].ForeignKey, lstOrderDtl[i].Key);
                            }

                        }
                        //设置ReqHdr Post标志
                        bllReqHdr.SetPosted(dbConOrder, intReqHdrID);

                        //dbConOrder.CommitTrans();
                    }
                    catch( Exception ex)
                    {
                        LogManager.Debug(ex.Message);
                        //dbConOrder.RollbackTrans();
                        throw;
                    }
                }

                ts.Complete();
            }
            

            return modelOrderHdr;
        }



        private poOrderDtlDataModel Post_InitDtl(poOrderDtlBLL bllOrderDtl, int intForeignKey, poReqDtlDataModel modelReqDtl)
        {
            if (modelReqDtl.ReqQty.CompareTo(0d) <= 0)
            {
                throw new MaxLeafException("数量不能为0");
            }
            poOrderDtlDataModel modelDtl = new poOrderDtlDataModel(
                intForeignKey
                , modelReqDtl.ItemId
                , modelReqDtl.UnitId
                , modelReqDtl.ReqQty
                , modelReqDtl.Cost
                , modelReqDtl.Subtotal
                , modelReqDtl.WebPrice
                , modelReqDtl.OrigCompanyID
                );

            return (poOrderDtlDataModel)bllOrderDtl.InsertFinterID(modelDtl);
        }

        private poOrderHdrDataModel Post_InitHdr(poOrderHdrBLL bllOrderHdr, poReqHdrDataModel modelReqHdr, int intEnterUserId)
        {
            poOrderHdrDataModel modelHdr = new poOrderHdrDataModel(
                modelReqHdr.CompanyID
                , intEnterUserId
                ,DateTime.Now
                , modelReqHdr.OrigCompanyID
               );
            return (poOrderHdrDataModel)bllOrderHdr.InsertFinterID(modelHdr);
        }
        
        public bool GeneratPoReqDtlFromStoresReq(imStoresReqHdrDataModel hdrModel, int intOrigCompanyID ,DBAccess dbOrdCon )
        {
            string strSQL = "";
            poReqHdrDataModel poReqHdrModel = new poReqHdrDataModel();
            strSQL = "select FinterID from poReqHdr where companyid='" + hdrModel.CompanyID + "' and depid='" + hdrModel.DepartID + "' and OrigCompanyID="+intOrigCompanyID+" and posted=0 and Is_Delete=0";
            int intKey = CvtFunc.ToInt(dbOrdCon.GetValue(strSQL));
            if (intKey > 0)
            {
                poReqHdrModel = (poReqHdrDataModel)new poReqHdrBLL().Select(poReqHdrModel, intKey);
            }
            else
            {
                poReqHdrModel = new poReqHdrDataModel(hdrModel.CompanyID, hdrModel.DepartID);
                poReqHdrModel.OrigCompanyID = intOrigCompanyID;
                poReqHdrModel = (poReqHdrDataModel)new poReqHdrBLL().InsertFinterID(poReqHdrModel);
            }
              
            imStoresReqDtlDataModel imDtlModel = new imStoresReqDtlDataModel();
            List<Object> imStoreReqDtl = (List<Object>)BaseBLL.GetDataModelBLL("imStoresReqDtlDataModel").SelectDtl(imDtlModel, hdrModel.Key);
            for (int i = 0; i <= imStoreReqDtl.Count-1; i++)
            {
                imStoresReqDtlDataModel imOrigStoreReqDtl = imStoreReqDtl[i] as imStoresReqDtlDataModel;
                if (imOrigStoreReqDtl.Is_Delete == true) continue;
                double dblAvail = ImInvLocBLL.GetAvail( ( poReqHdrModel.OrigCompanyID== 0 ? hdrModel.CompanyID :  poReqHdrModel.OrigCompanyID) , imOrigStoreReqDtl.ItemID, imOrigStoreReqDtl.UnitID, true, true);
                double dblOnOrder = ImInvLocBLL.GetOnOrder((poReqHdrModel.OrigCompanyID == 0 ? hdrModel.CompanyID : poReqHdrModel.OrigCompanyID), imOrigStoreReqDtl.ItemID, imOrigStoreReqDtl.UnitID);
                double dblComm = ImInvLocBLL.GetComm((poReqHdrModel.OrigCompanyID == 0 ? hdrModel.CompanyID : poReqHdrModel.OrigCompanyID), imOrigStoreReqDtl.ItemID, imOrigStoreReqDtl.UnitID);
                LogManager.Debug(string.Format("Onhand: {0} onorder: {1} comm: {2}", dblAvail, dblOnOrder, dblComm));
                double dblReqQty =dblComm-( dblAvail + dblOnOrder) ;                
                if (dblReqQty>0)
                {
                    if (dblReqQty > CvtFunc.ToDouble(dblReqQty, 0))
                    {
                        dblReqQty = CvtFunc.ToDouble(dblReqQty, 0) + 1;
                    }
                    else 
                    {
                        dblReqQty = CvtFunc.ToDouble(dblReqQty, 0) ;
                    }
                    poReqDtlDataModel poDtlModel = new poReqDtlDataModel();
                    poDtlModel.CompanyId = poReqHdrModel.CompanyID ;
                    poDtlModel.OrigCompanyID = poReqHdrModel.OrigCompanyID;
                    poDtlModel.DepID = hdrModel.DepartID ;
                    poDtlModel.ItemId = imOrigStoreReqDtl.ItemID;
                    poDtlModel.WebPrice = imOrigStoreReqDtl.WebPrice;
                    poDtlModel.Cost = imOrigStoreReqDtl.Price; //ImInvLocBLL.GetWtAvgCost(hdrModel.CompanyID , poDtlModel.ItemId , poDtlModel.UnitId) ;
                    poDtlModel.ForeignKey = poReqHdrModel.Key;
                    poDtlModel.ReqQty = dblReqQty;
                    poDtlModel.Subtotal = dblReqQty * imOrigStoreReqDtl.Price;
                    poDtlModel.UnitId = imOrigStoreReqDtl.UnitID;
                   
                    poDtlModel = (poReqDtlDataModel)new poReqDtlBLL().Add(poDtlModel);                    

                    strSQL = "UPDATE poReqDtl Set StoreReqDtlID= " + imOrigStoreReqDtl.Key + " where DtlID='" + poDtlModel.Key + "'";
                    dbOrdCon.ExecuteSql(strSQL); 
                }
            }            
            new poReqHdrBLL().Update(poReqHdrModel);

            strSQL = " Update poReqHdr Set Is_Delete=1 where companyid='" + hdrModel.CompanyID + "' and depid='" + hdrModel.DepartID + "' and posted=0 and Is_Delete=0 ";
            strSQL +=" And FInterID ='" + intKey + "' and ";
            strSQL +=" FInterID not in (select hdrid from PoReqDtl where companyid='" + hdrModel.CompanyID + "' and depid='" + hdrModel.DepartID + "' and HdrID='" + intKey + "')  ";
            dbOrdCon.ExecuteSql(strSQL); 

            return true;
        }
    }
}
